import 'dart:io';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:oktoast/oktoast.dart';
import '../../model/inputMessage.dart';
import 'package:sj001/pages/selectFile/selectFilePage.dart';

class InputTextfield extends StatefulWidget {
  InputTextfield({this.onSend,this.onNew,required this.isRequesting,Key? key}) : super(key: key);
  Function(InputMessageModel model)? onSend;
  Function()? onNew;
  RxBool isRequesting;
  @override
  State<InputTextfield> createState() => _InputTextfieldState();
}

class _InputTextfieldState extends State<InputTextfield> {
  InputMessageModel model = InputMessageModel.fromJson({});
  FocusNode focus = FocusNode();
  TextEditingController ctr = TextEditingController();
  RxBool hasFocus = true.obs;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    focusListener();
    ctr.text = model.content;

    focus.addListener(focusListener);
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    focus.removeListener(focusListener);
  }

  focusListener() {
    hasFocus.value = focus.hasFocus;
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: const BoxDecoration(
        color: Colors.white,
      ),
      padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
      child: Row(
        children: [
          Obx(
            () => Visibility(
              visible: !hasFocus.value,
              child: InkWell(onTap: onNew, child:const Padding(
                padding: EdgeInsets.only(right: 5),
                child: Icon(
                  Icons.message_rounded,
                  size: 30,
                ),
              ),),
            ),
          ),
          Expanded(
            child: Container(
              padding: const EdgeInsets.symmetric(
                horizontal: 10,
                vertical: 5,
              ),
              decoration: BoxDecoration(
                border: Border.all(
                  color: Colors.black,
                  width: 0.5,
                ),
                borderRadius: BorderRadius.circular(10),
              ),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Visibility(
                    visible: model.imgs.isNotEmpty,
                    child: Padding(
                      padding: const EdgeInsets.symmetric(vertical: 5),
                      child: GridView.builder(
                        shrinkWrap: true,
                        gridDelegate:
                            const SliverGridDelegateWithFixedCrossAxisCount(
                          mainAxisSpacing: 5,
                          crossAxisCount: 5,
                          childAspectRatio: 1,
                          crossAxisSpacing: 5,
                        ),
                        itemBuilder: (ctx, index) {
                          InputMessageFileData data = model.imgs[index];
                          return Container(
                            decoration: const BoxDecoration(
                              color: Colors.transparent,
                            ),
                            child: Stack(
                              children: [
                                Padding(
                                  padding:
                                      const EdgeInsets.only(top: 5, right: 5),
                                  child: Image.file(
                                    File(data.path ?? ''),
                                  ),
                                ),
                                Positioned(
                                  top: 0,
                                  right: 0,
                                  child: InkWell(
                                    onTap: () {
                                      setState(() {
                                        model.imgs.remove(data);
                                      });
                                    },
                                    child: Container(
                                      height: 12,
                                      width: 12,
                                      decoration: BoxDecoration(
                                        borderRadius: BorderRadius.circular(6),
                                        border: Border.all(
                                          color: Colors.black,
                                          width: 0.5,
                                        ),
                                      ),
                                      alignment: Alignment.center,
                                      child: const Icon(
                                        Icons.close_rounded,
                                        size: 10,
                                      ),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          );
                        },
                        itemCount: model.imgs.length,
                      ),
                    ),
                  ),
                  Visibility(
                    visible: model.files.isNotEmpty,
                    child: Padding(
                      padding: const EdgeInsets.symmetric(vertical: 5),
                      child: ListView.builder(
                        shrinkWrap: true,
                        itemBuilder: (ctx, index) {
                          InputMessageFileData data = model.files[index];
                          return Stack(
                            children: [
                              Container(
                                decoration: BoxDecoration(
                                  color: const Color(0x80eeeeee),
                                  borderRadius: BorderRadius.circular(5),
                                ),
                                padding: const EdgeInsets.all(5),
                                margin: const EdgeInsets.only(right: 5, top: 5),
                                child: Row(
                                  children: [
                                    const Padding(
                                      padding: EdgeInsets.only(right: 5),
                                      child: Icon(
                                        Icons.file_copy_outlined,
                                        size: 40,
                                      ),
                                    ),
                                    Expanded(
                                        child: Column(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      mainAxisSize: MainAxisSize.min,
                                      children: [
                                        Text(
                                          data.name ?? '',
                                          maxLines: 1,
                                          overflow: TextOverflow.ellipsis,
                                          style: const TextStyle(
                                            fontSize: 14,
                                          ),
                                        ),
                                        Text(
                                          '${((data.size ?? 0) / 1024).toStringAsFixed(2)}kb',
                                          style: const TextStyle(
                                              fontSize: 12,
                                              color: Color(0xffbbbbbb)),
                                        ),
                                      ],
                                    ))
                                  ],
                                ),
                              ),
                              Positioned(
                                top: 0,
                                right: 0,
                                child: InkWell(
                                  onTap: () {
                                    setState(() {
                                      model.files.remove(data);
                                    });
                                  },
                                  child: Container(
                                    height: 12,
                                    width: 12,
                                    decoration: BoxDecoration(
                                      borderRadius: BorderRadius.circular(6),
                                      border: Border.all(
                                        color: Colors.black,
                                        width: 0.5,
                                      ),
                                    ),
                                    alignment: Alignment.center,
                                    child: const Icon(
                                      Icons.close_rounded,
                                      size: 10,
                                    ),
                                  ),
                                ),
                              ),
                            ],
                          );
                        },
                        itemCount: model.files.length,
                      ),
                    ),
                  ),
                  TextField(
                    controller: ctr,
                    focusNode: focus,
                    maxLines: 5,
                    minLines: 1,
                    onChanged: (text){

                      if (text.endsWith('\n')){
                        text = text.substring(0,text.length-1);
                        ctr.text = text;
                        model.content = text;
                        onSend();
                      }else{
                        model.content = text;
                      }
                    },
                    decoration: const InputDecoration(
                        hintText: '输入您的问题或需求',
                        border: InputBorder.none,
                        filled: true,
                        fillColor: Colors.transparent,
                        contentPadding: EdgeInsets.symmetric(vertical: 5)),
                  ),
                ],
              ),
            ),
          ),
          InkWell(
            onTap: onSelectFile,
            child: const Padding(
              padding: EdgeInsets.only(left: 5),
              child: Icon(
                Icons.add_circle_outline_rounded,
                size: 30,
              ),
            ),
          ),
          InkWell(
            onTap: onSend,
            child: const Padding(
              padding: EdgeInsets.only(left: 5),
              child: Icon(
                Icons.send,
                size: 30,
              ),
            ),
          ),
        ],
      ),
    );
  }

  onNew(){
    clear();
    widget.onNew?.call();
  }

  onSend() {
    if (widget.isRequesting.value) {
      showToast('正在生成中...');
      return;
    }
    if (model.imgs.isEmpty && model.files.isEmpty && model.content.trim().isEmpty){
      return;
    }
    widget.onSend?.call(model);

    clear();
  }

  clear(){
    model = InputMessageModel(files: [], imgs: [], content: '');
    ctr.text = '';
    focus.unfocus();
    setState(() {
    });

  }

  onSelectFile() {
    if (model.files.length + model.imgs.length >= 10) {
      showToast('最多选择10个文件');
      return;
    }
    Get.to(() => SelectFilePage(callback: onFileCallback));
  }

  onFileCallback(InputMessageFileData data) {
    if (data.type == 1) {
      // 图片
      model.imgs.add(data);
    } else if (data.type == 2) {
      // 文件
      model.files.add(data);
    }
    setState(() {});
  }
}
